﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;

namespace devtm.Aop.Extensions
{

    public static class CustomAttributeExt
    {


        public static CustomAttribute GetAttribute(this IEnumerable<CustomAttribute> attributes, string attributeName)
        {
            return attributes.Where(attribute => attribute.Constructor.DeclaringType.Name == attributeName).FirstOrDefault();
        }


        public static bool ContainsAttribute(this IEnumerable<CustomAttribute> attributes, string attributeName)
        {
            return attributes.Any(attribute => attribute.Constructor.DeclaringType.Name == attributeName);
        }

        public static void SerializeArgument(this CustomAttributeNamedArgument customAttributeArgument, StringBuilder s)
        {
            s.Append(customAttributeArgument.Name);
            SerializeArgument(customAttributeArgument.Argument, s);
        }

        public static void SerializeArgument(this CustomAttributeArgument customAttributeArgument, StringBuilder s)
        {

            var item = customAttributeArgument.Value;

            if (item == null)
                s.Append("null");

            else
            {

                Type t = item.GetType();

                if (item is string)
                    s.Append(item as string);

                else if (t.IsClass)
                    s.Append(item.GetHashCode());

                else if (t.IsEnum)
                    s.Append((int)item);

                else
                    s.Append(item.ToString());
            }

        }

    }
}
